package org.lightcommons.orm;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.List;

import org.lightcommons.util.ReflectionUtils;

public class DefaultDao<T, ID extends Serializable> implements Dao<T, ID> {
//	private static final Log log = LogFactory.getLog(AbstractGenericDao.class);
	private final Class<T> entityClass;
	private final Class<ID> idClass;
	protected final DaoTemplate daoTemplate;
	
	public DefaultDao(DaoTemplate daoTemplate) {
		super();
		Type[] types = ReflectionUtils.findParameterizedTypes(getClass(), DefaultDao.class);
		entityClass=ReflectionUtils.getRawClass(types[0]);
		idClass=ReflectionUtils.getRawClass(types[1]);
		this.daoTemplate = daoTemplate;
	}

	/**
	 * @param entityClass
	 * @param idClass
	 */
	public DefaultDao(DaoTemplate daoTemplate,Class<T> entityClass, Class<ID> idClass) {
		super();
		this.entityClass = entityClass;
		this.idClass = idClass;
		this.daoTemplate = daoTemplate;
	}

	public ID save(T entity) {
		return (ID) daoTemplate.save(entity);
	}

	public void update(T entity) {
		daoTemplate.update(entity);
	}

	public T delete(T entity) {
		return daoTemplate.delete(entity);
	}

	public T deleteById(ID id) {
		return daoTemplate.deleteById(entityClass, id);
	}
	
	public List<T> findAll() {
		return daoTemplate.findAll(entityClass);
	}
	
	protected final Class<T> getEntityClass() {
		return entityClass;
	}
	
	protected final Class<ID> getIdClass() {
		return idClass;
	}

	public T get(ID id) {
		return daoTemplate.get(entityClass, id);
	}

	public Page<T> getPage(int pageIndex, int maxResults) {
		return daoTemplate.getPage(entityClass, pageIndex, maxResults);
	}

	public void saveOrUpdate(T entity) {
		daoTemplate.saveOrUpdate(entity);
	}

	public Page<T> getPageByKeyWord(String inculdKeywords,
			String excludeKeywords, int pageIndex, int maxResults) {
		return daoTemplate.getPageByKeyWord(entityClass, inculdKeywords, excludeKeywords, pageIndex, maxResults);
	}
	
	public Page<T> getPage(int pageIndex, int maxResults, String orderBy,
				boolean desc) {
		return daoTemplate.getPage(entityClass, pageIndex, maxResults, orderBy, desc);
	}
}
